//
//  HZLocation.m
//  HZCityPicker
//
//  Created by 黄泽 on 2017/7/14.
//  Copyright © 2017年 黄泽. All rights reserved.
//

#import "HZLocation.h"
#import <CoreLocation/CoreLocation.h>

@interface HZLocation ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property(nonatomic, assign) NSInteger pushNumber;
@end

@implementation HZLocation

- (instancetype)init {
    if (self = [super init]) {
        [self startPositioningSystem];
    }
    return self;
}

- (void)startPositioningSystem {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    [self.locationManager startUpdatingLocation];
    //[_locationManager requestLocation];//只能定位一次 且实现 didFailWithError 方法 定位速度比较慢
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        [_locationManager requestWhenInUseAuthorization];
        [_locationManager requestAlwaysAuthorization];
    }
    //要想继续获取位置，需要使用以下属性进行设置（注意勾选后台模式：location）但会出现蓝条
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        //_locationManager.allowsBackgroundLocationUpdates = YES;
    }
}

#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            //app第一次启动时候弹出提示允许权限前的状态、不点击杀死app启动会有一次启动提示框
            NSLog(@"kCLAuthorizationStatusNotDetermined");
            break;
        case kCLAuthorizationStatusRestricted:
            NSLog(@"kCLAuthorizationStatusRestricted");
            break;
        case kCLAuthorizationStatusDenied:
            //用户“不允许“定位授权
            NSLog(@"kCLAuthorizationStatusDenied");
            if([CLLocationManager locationServicesEnabled]) {
                NSLog(@"定位开启，但被拒");
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"请到设置->隐私->定位服务中开启【%@】定位服务，以便于距离筛选能够准确获得你的位置信息",[Utilities getAPPName]] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                    }
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alert addAction:cancleAction];
                [alert addAction:sureAction];
                [[Utilities topViewController] presentViewController:alert animated:YES completion:nil];
            } else {
                NSLog(@"定位关闭，不可用");
            }
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            //用户“使用App时允许“定位授权
            NSLog(@"kCLAuthorizationStatusAuthorizedAlways");
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            //用户“允许一次“定位授权、每次app重启会弹出框
            NSLog(@"kCLAuthorizationStatusAuthorizedAlways");
            break;
        default:
            break;
    }
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (self.delegate && [self.delegate respondsToSelector:@selector(locating)]) {
            [self.delegate locating];
        }
    });
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:[locations lastObject] completionHandler:^(NSArray *placemarks, NSError *error) {
        
        if (placemarks.count > 0) {
            CLPlacemark * placemark = placemarks.firstObject;
            NSDictionary *location = [placemark addressDictionary];
            CLLocationCoordinate2D coordinate = [placemark location].coordinate;
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(currentLocation:coordinate:)] && self.pushNumber == 0) {
                self.pushNumber += 1;
                [self.delegate currentLocation:location coordinate:coordinate];
            }
            [manager stopUpdatingLocation];
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if ([error code] == kCLErrorDenied) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(refuseToUsePositioningSystem:)]) {
            [self.delegate refuseToUsePositioningSystem:@"已拒绝使用定位系统"];
        }
    }
    if ([error code] == kCLErrorLocationUnknown) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            if (self.delegate && [self.delegate respondsToSelector:@selector(locateFailure:)]) {
                [self.delegate locateFailure:@"无法获取位置信息"];
            }
        });
    }
}
@end
